package com.huawang.mdesign.model.service.vo;

import com.huawang.mdesign.model.service.config.WebLog;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class ControllerStatistics {

    private final AtomicLong requestCount = new AtomicLong(0);

    private final AtomicLong totalTime = new AtomicLong(0);

    private final List<Long> spendTimeList = new ArrayList<>(2048);

    private final WebLog webInfo;

    public ControllerStatistics(WebLog log) {
        this.webInfo = log;
    }

    public void addRequestCount() {
        requestCount.incrementAndGet();
    }

    public void addSpendTimeList(long spendTime) {
        totalTime.addAndGet(spendTime);
        spendTimeList.add(spendTime);
    }

    public long getRequestCount() {
        return requestCount.get();
    }

    public String getUri() {
        return webInfo.getUri();
    }

    public long getAverageTime() {
        if (spendTimeList.isEmpty()) {
            return 0;
        }

        return totalTime.get() / spendTimeList.size();
    }

    public long getNinetyAverageTime() {
        return (long) spendTimeList.stream().sorted().limit((long) (spendTimeList.size() * 0.9)).mapToLong(it -> it).average()
                .orElse(0.0);
    }
}
